<template>
  <div class="top">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/Classification">课程管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>课程信息管理</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="middle">
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline form-search">
      <el-form-item label="课程名称">
        <el-input
          v-model="queryInfo.courseName"
          placeholder="请输入课程名称"
          clearable
          @clear="querydata"
        />
      </el-form-item>
      <el-form-item label="课程分类">
        <el-select v-model="queryInfo.courseClassifyName" clearable placeholder="请选择课程分类">
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="咨询师">
        <el-select v-model="queryInfo.counselorName" clearable placeholder="请选择咨询师">
          <el-option
            v-for="item in counselorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="querydata">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="add">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="remove" :disabled="multipleSelection.length === 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
  </div>

  <div class="bottom">
    <el-table
      :data="tableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      border
      stripe
      class="course-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="课程ID" width="100" align="center" />
      <el-table-column prop="name" label="课程名称" width="120" align="center" />
      <el-table-column prop="url" label="封面" width="100" align="center">
        <template #default="scope">
          <img
            v-if="scope.row.url"
            :src="`http://localhost:8080${scope.row.url}`"
            style="width: 40px; height: 40px; border-radius: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTimeStr" label="时长" width="100" align="center" />
      <el-table-column prop="videoNum" label="视频数" width="100" align="center" />
      <el-table-column prop="studyNum" label="学习人数" width="100" align="center" />
      <el-table-column
        prop="description"
        label="简介"
        width="150"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column prop="suitable" label="适用人群" width="120" align="center" />
      <el-table-column prop="gain" label="课程收获" width="120" align="center" />
      <el-table-column prop="learnNotice" label="学习须知" width="120" align="center" />
      <el-table-column prop="price" label="原价" width="100" align="center" />
      <el-table-column prop="discountPrice" label="折扣价" width="100" align="center" />
      <el-table-column prop="categoryName" label="分类" width="120" align="center" />
      <el-table-column prop="counselorName" label="心理导师名" width="120" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="editdata(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deletedata(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="Title" width="600">
    <el-form :model="form" label-width="120px" class="dialog-form">
      <el-form-item label="课程名称" required>
        <el-input v-model="form.name" autocomplete="off" placeholder="请输入课程名称" />
      </el-form-item>

      <el-form-item label="课程封面">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/upload"
          :show-file-list="false"
          :on-success="handleCoverUploadSuccess"
          accept="image/*"
        >
          <img v-if="form.url" :src="`http://localhost:8080${form.url}`" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">点击上传封面图片，支持 jpg、png 格式</div>
      </el-form-item>

      <el-form-item label="课程简介">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入课程简介"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="适用人群">
        <el-input v-model="form.suitable" autocomplete="off" placeholder="如：心理咨询师、学生等" />
      </el-form-item>

      <el-form-item label="课程收获">
        <el-input v-model="form.gain" autocomplete="off" placeholder="如：掌握心理咨询技能" />
      </el-form-item>

      <el-form-item label="学习须知">
        <el-input v-model="form.learnNotice" autocomplete="off" placeholder="如：需要心理学基础" />
      </el-form-item>

      <el-form-item label="原价">
        <el-input-number v-model="form.price" :min="0" :precision="2" placeholder="原价" />
      </el-form-item>

      <el-form-item label="折扣价">
        <el-input-number
          v-model="form.discountPrice"
          :min="0"
          :precision="2"
          placeholder="折扣价"
        />
      </el-form-item>

      <el-form-item label="课程分类" required>
        <el-select v-model="form.categoryId" placeholder="请选择课程分类" style="width: 100%">
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="咨询师" required>
        <el-select v-model="form.counselorId" placeholder="请选择咨询师" style="width: 100%">
          <el-option
            v-for="item in counselorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancle">取消</el-button>
        <el-button type="primary" @click="addform">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive } from 'vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
import type { ComponentSize } from 'element-plus'
const multipleTableRef = ref<TableInstance>()
const queryInfo = reactive({
  id: 0,
  courseName: '',
  courseTime: 0,
  courseCount: 0,
  learnCount: 0,
  courseIntro: '',
  applicableGroup: '',
  learningGain: '',
  notice: '',
  coursePrice: 0,
  courseClassifyName: '',
  courseClassifyId: '',
  counselorName: '',
  pageSize: 10,
  pageNum: 1,
})
const tableData = ref([])
const total = ref(0)
const Title = ref('')
const axios = getCurrentInstance().appContext.config.globalProperties.axios
const querydata = () => {
  axios
    .post(
      'course/page',
      {
        name: queryInfo.courseName,
        categoryName: queryInfo.courseClassifyName,
        counselorName: queryInfo.counselorName,
      },
      {
        params: {
          pageNum: queryInfo.pageNum,
          pageSize: queryInfo.pageSize,
        },
      },
    )
    .then((resp) => {
      console.log(resp)
      if (resp.code == 200) {
        console.log(resp)
        tableData.value = resp.data.list
        total.value = resp.data.total
      }
    })
}
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  queryInfo.pageSize = val
  querydata()
}
const handleCurrentChange = (val: number) => {
  queryInfo.pageNum = val
  querydata()
}

const dialogFormVisible = ref(false)

const formLabelWidth = '140px'

const form = ref({
  id: null,
  name: '',
  url: '',
  timeStr: '',
  videoNum: 0,
  studyNum: 0,
  description: '',
  suitable: '',
  gain: '',
  learnNotice: '',
  price: 0,
  discountPrice: 0,
  categoryId: null,
  counselorId: null,
})
const categoryOptions = ref([])
const counselorOptions = ref([])
const fetchCategoryOptions = () => {
  axios.get('courseClassification').then((resp) => {
    console.log(resp)
    if (resp.code === 200) {
      categoryOptions.value = resp.data.map((item) => ({
        label: item.name,
        value: item.id,
      }))
    }
  })
}
const fetchCounselorOptions = () => {
  axios.get('counselor').then((resp) => {
    console.log('咨询师数据:', resp)
    if (resp.code === 200) {
      counselorOptions.value = resp.data.map((item) => ({
        label: item.name,
        value: item.id,
      }))
    }
  })
}
onMounted(() => {
  fetchCategoryOptions()
  fetchCounselorOptions()
  querydata()
})
function handleCoverUploadSuccess(response) {
  console.log('图片上传响应:', response)
  // 兼容多种后端返回格式
  const imageUrl = response.url || response.data || response.message
  if (imageUrl) {
    form.value.url = imageUrl
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error('封面上传失败，未获取到图片地址')
  }
}
const add = () => {
  Title.value = '新增课程'
  dialogFormVisible.value = true

  // 确保下拉选项已加载
  if (categoryOptions.value.length === 0) {
    fetchCategoryOptions()
  }
  if (counselorOptions.value.length === 0) {
    fetchCounselorOptions()
  }

  // 重置表单数据
  form.value = {
    id: null,
    name: '',
    url: '',
    timeStr: '',
    videoNum: 0,
    studyNum: 0,
    description: '',
    suitable: '',
    gain: '',
    learnNotice: '',
    price: 0,
    discountPrice: 0,
    categoryId: null,
    counselorId: null,
  }
}
const cancle = () => {
  form.value = {
    id: null,
    name: '',
    url: '',
    timeStr: '',
    videoNum: 0,
    studyNum: 0,
    description: '',
    suitable: '',
    gain: '',
    learnNotice: '',
    price: 0,
    discountPrice: 0,
    categoryId: null,
    counselorId: null,
  }
  dialogFormVisible.value = false
}
const addform = () => {
  // 表单验证
  if (!form.value.name.trim()) {
    ElMessage.warning('请输入课程名称')
    return
  }
  if (!form.value.categoryId) {
    ElMessage.warning('请选择课程分类')
    return
  }
  if (!form.value.counselorId) {
    ElMessage.warning('请选择咨询师')
    return
  }

  // 价格验证
  if (form.value.price < 0) {
    ElMessage.warning('原价不能为负数')
    return
  }
  if (form.value.discountPrice < 0) {
    ElMessage.warning('折扣价不能为负数')
    return
  }
  if (form.value.discountPrice > form.value.price) {
    ElMessage.warning('折扣价不能高于原价')
    return
  }

  // 数字字段验证
  if (form.value.videoNum < 0) {
    ElMessage.warning('视频数量不能为负数')
    return
  }
  if (form.value.studyNum < 0) {
    ElMessage.warning('学习人数不能为负数')
    return
  }

  if (form.value.id) {
    // 编辑操作
    axios
      .put('course', form.value)
      .then((resp) => {
        console.log('编辑响应:', resp)
        if (resp.code == 200) {
          dialogFormVisible.value = false
          querydata()
          ElMessage.success('编辑成功')
        } else {
          ElMessage.error(resp.message || '编辑失败')
        }
      })
      .catch((error) => {
        console.error('Error:', error)
        ElMessage.error('请求出错，请重试')
      })
  } else {
    // 新增操作
    axios
      .post('course', form.value)
      .then((resp) => {
        console.log('新增响应:', resp)
        if (resp.code == 200) {
          dialogFormVisible.value = false
          querydata()
          ElMessage.success('新增成功')
        } else {
          ElMessage.error(resp.message || '新增失败')
        }
      })
      .catch((error) => {
        console.error('Error:', error)
        ElMessage.error('请求出错，请重试')
      })
  }
}
const editdata = (row) => {
  console.log('编辑行数据:', row)
  Title.value = '编辑课程'
  dialogFormVisible.value = true

  // 确保下拉选项已加载
  if (categoryOptions.value.length === 0) {
    fetchCategoryOptions()
  }
  if (counselorOptions.value.length === 0) {
    fetchCounselorOptions()
  }

  // 深拷贝避免直接修改原数据
  form.value = {
    id: row.id,
    name: row.name || '',
    url: row.url || '',
    timeStr: row.timeStr || '',
    videoNum: row.videoNum || 0,
    studyNum: row.studyNum || 0,
    description: row.description || '',
    suitable: row.suitable || '',
    gain: row.gain || '',
    learnNotice: row.learnNotice || '',
    price: row.price || 0,
    discountPrice: row.discountPrice || 0,
    categoryId: row.categoryId || null,
    counselorId: row.counselorId || null,
  }

  // 延迟设置，确保下拉选项已渲染
  setTimeout(() => {
    console.log('表单数据已设置:', form.value)
  }, 100)
}

const deletedata = (id) => {
  ElMessageBox.confirm('确定要删除此课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete(`course/${id}`)
        .then((resp) => {
          if (resp.code == 200) {
            querydata()
            ElMessage.success('删除成功')
          } else {
            ElMessage.error('删除失败')
          }
        })
        .catch((error) => {
          console.error('Error:', error)
          ElMessage.error('请求出错，请重试')
        })
    })
    .catch(() => {
      // 用户取消操作
    })
}

const remove = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的课程')
    return
  }
  ElMessageBox.confirm('确定要批量删除选中的课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const ids = multipleSelection.value.map((item) => item.id).join(',')
      axios
        .delete(`course/batch`, {
          params: { ids },
        })
        .then((resp) => {
          if (resp.code == 200) {
            querydata()
            ElMessage.success('批量删除成功')
          } else {
            ElMessage.error('批量删除失败')
          }
        })
        .catch((error) => {
          console.error('Error:', error)
          ElMessage.error('请求出错，请重试')
        })
    })
    .catch(() => {
      // 用户取消操作
    })
}
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
</script>

<style scoped>
.top {
  margin-bottom: 20px;
}
.form-search {
  background: #fff;
  padding: 20px 24px 0 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}
.middle {
  margin-bottom: 20px;
}
.course-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}
.demo-pagination-block {
  margin: 24px 0 0 0;
  text-align: right;
}
.dialog-form {
  padding-top: 10px;
}
.el-select {
  width: 150px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 8px;
  object-fit: cover;
  border: 2px dashed #d9d9d9;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader .avatar:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: center;
}

.dialog-form .el-form-item {
  margin-bottom: 20px;
}

.dialog-form .el-input-number {
  width: 100%;
}
</style>
